<template>
  <el-input style="width: 20em" maxlength="8" show-word-limit v-model="input"
            placeholder="请输入老师发送的班级唯一代码">
  </el-input>
  <el-button type="primary" style="margin-left: 1em" @click="clickFind">查找</el-button>

  <el-popover trigger="click">
    <el-button type="primary" @click="join">加入</el-button>
    <template #reference>
      <div id="findClassResult" v-if="!findNothing && findClass!=undefined">
        <p>{{ (findClass as Class).name }}</p>
        <p style="color: #ccc">{{ (findClass as Class).code }}</p>
      </div>
    </template>
  </el-popover>
  <p v-if="findNothing">没有找到任何班级</p>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {Class, MyDialog} from "../../types/mytypes";
import {ClassRequest} from "../../request/MyRequset";
import {UserStore} from "../../store/store";

const emit = defineEmits(["success", "error"])

let input = ref('')
let findClass = ref<Class | undefined>(undefined)
let findNothing = ref(false)

const join = async () => {
  let joinRes = await ClassRequest.join(
      UserStore.getUser().id,
      (findClass.value as Class).id,
      false
  )
  let dialog:MyDialog = {
    msg:"",
    show:true,
    suc:false
  };
  console.log(joinRes)
  if(joinRes.suc){
    dialog.suc = true;
    dialog.msg="加入班级成功"
    emit("success",dialog)
  }else{
    dialog.msg=joinRes.message
    emit("error",dialog)
  }
}

const clickFind = async () => {
  let findRes = await ClassRequest.getByCode(input.value)
  if (findRes.suc) {
    if (findRes.data != undefined) {
      findNothing.value = false
      findClass.value = findRes.data
    } else {
      findNothing.value = true
    }
  } else {
    let dialog: MyDialog = {
      msg: findRes.message,
      show: true,
      suc:false
    }
    emit("error", dialog)
  }
}
</script>

<style scoped lang="scss">
#findClassResult {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 61%;
  height: 4em;
  padding: 0 10px;
  border-radius: 4px;
  border: 1px #ececec solid;
  margin-top: 1em;
  user-select: none;
}

#findClassResult:hover {
  border: 1px #409eff solid;
  cursor: pointer;
}
</style>